var lk_card_obj = null;
var icdev = -1;
var gl_sector = 13;
var gl_BinBlock = gl_sector * 4;
var key_cache = null;

var readerObj = {
    connected : function () {
      return icdev !== -1;
    },
    
    readCardNo : function (callback) {

        readerObj.readNoCallback = callback;
        if(lk_card_obj){
            lk_card_obj.findcardHex(icdev,0);
        }
    },

    /**
     * 必须要在操作卡前调用一次，将秘钥下载到发卡器中
     * @param key
     */
    setSecurtyKey : function (key,callback) {
        if(lk_card_obj && key != key_cache){
            key_cache = key;
            /* 先默认为空卡，写卡失败再尝试key_cache */
            readerObj.loadKey("FFFFFFFFFFFF",callback);
        }else{
            if(callback)
                callback();
        }
    },

    loadKey : function (key,callback) {
        readerObj.loadKeyCallback = callback;
        lk_card_obj.loadkey(icdev,0,gl_sector,key);
    },

    /**
     * 验证卡与发卡器扇区密码是否匹配，匹配后才可能操作卡
     * @param callback
     */
    authCard : function (success,failed) {
        readerObj.authCardSuccessCallback = success;
        readerObj.authCardFailedCallback = failed;
        if(lk_card_obj) {
            lk_card_obj.authentication(icdev, 0, gl_sector);
        }
    },

    /**
     * 更新秘钥
     * @param authed 是否已经验证过秘钥
     */
    updateKey : function (authed,callback,key) {
        readerObj.updateKeyCallback = callback;
        if(!authed){
            this.authCard(function () {
                lk_card_obj.changkey(icdev,gl_sector,key,"FF078069",0,key);
            })
        }else{
            lk_card_obj.changkey(icdev,gl_sector,key,"FF078069",0,key);
        }
    },

    /**
     * 写卡权限，必须先调用setSecurtyKey
     * 需要先读卡，确定卡存在，再校验卡秘钥，再写卡操作
     * @param data
     */
    writeCard : function (authStr,cardType,cardNo,callback) {
        readerObj.writeCardCallback = function () {
            readerObj.updateKey(true,function () {
                lk_card_obj.beep(icdev,10);
                if(callback)
                    callback();
            },key_cache);
        };
        readerObj.readCardNo(function (card) {

            if(card.length === 0){
                layui.layer.msg("未读到卡!")
                return;
            }else if(cardNo !== card){
                layui.layer.msg("卡号不匹配["+cardNo+"] 与 ["+card+"]");
                return;
            }
            readerObj.authCard(
                function () {
                    if(lk_card_obj) {
                        authStr = cardType === 1?"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF":authStr;
                        var len = 32 - authStr.length;
                        if (len > 0) {
                            for (var i = 0; i < len; i++) {
                                authStr = '0' + authStr;
                            }
                        }
                        lk_card_obj.write(icdev, gl_BinBlock, authStr);
                    }
                },
                function () {
                    if(key_cache) {
                        /* 假如第一次验证空卡失败，则再次验证我们需要写入的秘钥 */
                        readerObj.loadKey(key_cache, function () {
                            key_cache = null;
                            readerObj.writeCard(authStr,cardType,cardNo,callback);
                        })
                    }

                }
            )
        })

    },

    resumeCard : function (callback) {
        readerObj.readCardNo(function (card) {

            if(card.length === 0){
                layui.layer.msg("未读到卡!")
                return;
            }

            readerObj.authCard(
                function () {
                    if(key_cache){
                        if(callback)
                            callback("本身就为空卡，不需要恢复");
                    }else {
                        /* 最后一步，恢复成白卡秘钥 */
                        readerObj.updateKey(true, function (result) {
                            if(result === 0) {
                                lk_card_obj.beep(icdev, 10);
                                if (callback)
                                    callback();
                            }else{
                                if(callback)
                                    callback("恢复失败");
                            }
                        },"FFFFFFFFFFFF");


                    }
                },
                function () {
                    if(key_cache) {
                        /* 假如第一次验证空卡失败，则再次验证我们需要写入的秘钥 */
                        readerObj.loadKey(key_cache, function () {
                            key_cache = null;
                            readerObj.resumeCard(callback);
                        })
                    }

                }
            )
        })

    },

    exit : function (callback) {
        readerObj.exitCallback = callback;
        lk_card_obj.exit(icdev);
    }
};

/**
 * 莱卡浏览器与本地服务端socket通讯的统一回调接口
 * @param rData 返回的数据
 */
function cmdResultCallback(rData) {

    switch (rData.FunctionID) {
        case FUNCIDS._fid_adaptReader:
            lk_card_obj.initialcom(100,115200);
            break;
        case FUNCIDS._fid_initialcom:
            var rel = rData.RePara_Int;
            if(0 == rel)
            {
                var hdev = parseInt(rData.RePara_Str);
                if(hdev != -1)
                {
                    icdev= hdev;
                    lk_card_obj.beep(icdev,10);   //do a beep
                }
            }
            else
                layui.layer.alert("初始化失败");
            break;

        case FUNCIDS._fid_findCardHex:
            var strcard= rData.RePara_Str;
            if(readerObj.readNoCallback)
                readerObj.readNoCallback(strcard);
            break;
        case FUNCIDS._fid_authenClass:
            var rel = rData.RePara_Int;
            if(0 == rel)
            {
                if(readerObj.authCardSuccessCallback)
                    readerObj.authCardSuccessCallback();
            }
            else if(key_cache) {
                if(readerObj.authCardFailedCallback)
                    readerObj.authCardFailedCallback();
            }else{
                layui.layer.alert("卡秘钥不匹配，请确认是否该小区的卡!");
            }
            break;
        case FUNCIDS._fid_writeAsStr:
            if(readerObj.writeCardCallback)
                readerObj.writeCardCallback();
            break;
        case FUNCIDS._fid_exit:
            if(readerObj.exitCallback)
                readerObj.exitCallback();
            break;
        case FUNCIDS._fid_loadKey:
            if(readerObj.loadKeyCallback)
                readerObj.loadKeyCallback();
            break;
        case FUNCIDS._fid_changeKey:
            if(readerObj.updateKeyCallback)
                readerObj.updateKeyCallback(rData.RePara_Int);
            break;
    }
}


/**
 * 发卡器初始化与连接本地服务器
 * @returns {{readNo: (function(this:readerObj))}}
 */
function lk_init(socketEventCallback) {
    if(!lk_card_obj) {
        lk_card_obj = embed_reader.getOBJ(READER_TYPE._reader_type_contactLess);
        lk_card_obj.onResult(cmdResultCallback);
        lk_card_obj.socketEvent = socketEventCallback;
    }
    try{

        return readerObj;

    }catch(e){layui.layer.alert(e.message);}
    
}